package com.example.demo.service.io;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 使用BIO模型编写一个服务器端，监听6666端口，当有客户端连接时，就启动一个线程与之通讯。
 * 要求使用线程池机制改善，可以连接多个客户端.
 *
 * 服务器端可以接收客户端发送的数据(telnet 方式即可)。
 */
public class BIOServer {

	public static void main(String[] args) throws Exception {
		
		//����һ���̳߳�,ÿ���ӵ�һ���ͻ��ˣ�������һ���̺߳Ϳͻ��˽���ͨ��
		ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
		
		@SuppressWarnings("resource")
		ServerSocket server=new ServerSocket(6666);
		System.out.println("tomcat����������...");
		while(true){
			//������ �ȴ��ͻ�������
			final Socket socket = server.accept();
			System.out.println("���ӵ�һ���ͻ��ˣ�");
			newCachedThreadPool.execute(new Runnable() {
				
				@Override
				public void run() {
					//ҵ����
					handler(socket);
				}
			});
		}
		
	}
	
	/**
	 * ����
	 * @param socket
	 */
	public static void handler(Socket socket){
			try {
				byte[] bytes = new byte[1024];
				InputStream inputStream = socket.getInputStream();
				
				while(true){
					//���ͻ������� ����
					int read = inputStream.read(bytes);
					if(read != -1){
						System.out.println(new String(bytes, 0, read));
					}else{
						break;
					}
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				try {
					System.out.println("�رպ�client������..");
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
	}

}
